package com.cg.leetcode;

import org.junit.Test;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 19.删除链表的倒数第N个节点
 *
 * @program: LeetCode->LeetCode_19
 * @description: 19.删除链表的倒数第N个节点
 * @author: cg
 * @create: 2021-08-31 21:18
 **/
public class LeetCode_19 {

    @Test
    public void test19() {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4,new ListNode(5)))));
        System.out.println(head);
        System.out.println(removeNthFromEnd(head, 2));
    }

    /**
     * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
     * <p>
     * 进阶：你能尝试使用一趟扫描实现吗？
     * <p>
     * 示例 1：
     * <p>
     * 输入：head = [1,2,3,4,5], n = 2
     * 输出：[1,2,3,5]
     * <p>
     * 示例 2：
     * 输入：head = [1], n = 1
     * 输出：[]
     * <p>
     * 示例 3：
     * 输入：head = [1,2], n = 1
     * 输出：[1]
     * <p>
     * 提示：
     * 1) 链表中结点的数目为 sz
     * 2) 1 <= sz <= 30
     * 3) 0 <= Node.val <= 100
     * 4) 1 <= n <= sz
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //通过双指针解决
        ListNode dummy = new ListNode(0, head);
        ListNode first = head;
        ListNode second = dummy;
        for (int i = 0; i < n; ++i) {
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return dummy.next;
    }
    /*public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode first = head;
        ListNode second = dummy;
        for (int i = 0; i < n; ++i) {
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return dummy.next;
    }*/
    /*public ListNode removeNthFromEnd(ListNode head, int n) {
        //通过栈解决
        ListNode dummy = new ListNode(0, head);
        Deque<ListNode> stack = new LinkedList<ListNode>();
        ListNode cur = dummy;
        while (cur != null) {
            stack.push(cur);
            cur = cur.next;
        }
        for (int i = 0; i < n; ++i) {
            stack.pop();
        }
        ListNode prev = stack.peek();
        prev.next = prev.next.next;
        ListNode ans = dummy.next;
        return ans;
    }*/
    /*public ListNode removeNthFromEnd(ListNode head, int n) {
        //通过链表长度解决
        ListNode dummy = new ListNode(0, head);
        int length = getLength(head);
        ListNode cur = dummy;
        for (int i = 1; i < length - n + 1; ++i) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        return dummy.next;
    }

    public int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            ++length;
            head = head.next;
        }
        return length;
    }*/

}
